package com.zhouyibike.uu.ui.activity.mywallet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.ChongZhiListResult;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.entity.PayForRegisterResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.adapter.ChongZhiListAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class ChongZhiActivity extends BaseActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{
    private ImageButton mBtnBack;
    private TextView mBtnTitle,xieyi;

    private ChongZhiListAdapter chongZhiListAdapter ;
    private GridView gv_list;
    private CheckBox cb_wx,cb_zfb;
    private String paytype="1";
    private int chongzhiid;
    private Button btn_zhifu;
    private IWXAPI api;
    private String payamont;
    private boolean isformmaincz;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        isformmaincz=getIntent().getBooleanExtra("isformmaincz",false);
        setContentView(R.layout.activity_chong_zhi);
        initView();
        getMsg();
        xieyi= (TextView) findViewById(R.id.xieyi);
        xieyi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getWZMsg("9","骑行充值协议");
            }
        });
    }
    private void initView() {
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("充值");
        mBtnBack.setOnClickListener(this);
        gv_list= (GridView) findViewById(R.id.gv_chongzhi_list);
        cb_wx= (CheckBox) findViewById(R.id.cb_chongzhi_wx);
        cb_wx.setOnCheckedChangeListener(this);
        cb_zfb= (CheckBox) findViewById(R.id.cb_chongzhi_zfb);
        cb_zfb.setOnCheckedChangeListener(this);
        btn_zhifu= (Button) findViewById(R.id.btn_chongzhiactivity_zhifu);
        btn_zhifu.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_chongzhiactivity_zhifu:
                chongzhi();
                break;
        }
    }
    private void chongzhi(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        params.put("id",chongzhiid+"");
        params.put("payType",paytype);
        showProgressDialog();
        addSubscription(apiStores.SaveRecharge(params),
                new ApiCallback<PayForRegisterResult>() {

                    @Override
                    public void onSuccess(PayForRegisterResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
//                            paysuccess();
                            if(paytype.equals("2")){
                                zfbpay(model.getData().getContent());
                            }else{
                                wxpay(model);
                            }
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    private void getMsg(){
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token",""));
        showProgressDialog();
        addSubscription(apiStores.GetRechargeList(params),
                new ApiCallback<ChongZhiListResult>() {

                    @Override
                    public void onSuccess(ChongZhiListResult model) {
                        if(model.getStatus()== Config.SUCCESSCODE){
                            initList(model);
                        }else{
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);

                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
    private void initList(ChongZhiListResult model){
        chongZhiListAdapter=new ChongZhiListAdapter(this,model.getData());
        gv_list.setAdapter(chongZhiListAdapter);
        gv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView tv_amont= (TextView) view.findViewById(R.id.tv_itemchongzhi_p);
                payamont=tv_amont.getTag().toString();
                btn_zhifu.setEnabled(true);
                chongzhiid=Integer.parseInt(view.getTag().toString());
                chongZhiListAdapter.setpreid(chongzhiid);
            }
        });
    }
    private void paysuccess(){
        setResult(1);
        Intent intent=new Intent(this,CZSuccessActivity.class);
        intent.putExtra("payamont",payamont);
        startActivityForResult(intent,400);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==400&&resultCode==1){
            if(isformmaincz){
                startActivity(new Intent(ChongZhiActivity.this,MyWalletActivity4.class));
                setResult(1);
            }else {
                setResult(1);
                finish();
            }
        }else if(requestCode==400&&resultCode==2){
            if(isformmaincz){
                setResult(1);
                finish();
            }else {
                setResult(2);
                finish();
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.cb_chongzhi_wx:
                if(isChecked){
                    cb_zfb.setChecked(false);
                    paytype="1";
                }else{
                    cb_zfb.setChecked(true);
                    paytype="2";
                }
                break;
            case R.id.cb_chongzhi_zfb:
                if(isChecked){
                    cb_wx.setChecked(false);
                    paytype="2";
                }else{
                    cb_wx.setChecked(true);
                    paytype="1";
                }
                break;
        }
    }
    private void wxpay(PayForRegisterResult model){
        api.registerApp( model.getData().getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if(!isPaySupported){
            Toast.makeText(ChongZhiActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(ChongZhiActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try{
            PayReq request = new PayReq();

            request.appId = model.getData().getAppId();

            request.partnerId = model.getData().getPartnerId();

            request.prepayId= model.getData().getPrepayId();

            request.packageValue ="Sign=WXPay";

            request.nonceStr= model.getData().getNoncestr();

            request.timeStamp=model.getData().getTimestamp();

            request.sign= model.getData().getSign();

            api.sendReq(request);

        }catch(Exception e){
            Toast.makeText(ChongZhiActivity.this, "异常："+e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if(progress==0){//支付成功
            paysuccess();
        }else{
            Toast.makeText(ChongZhiActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }
    private void zfbpay(final String orderinfo){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(ChongZhiActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ChongZhiActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    private void getWZMsg(String type, final String name) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", type);
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(ChongZhiActivity.this, TotalWebActivity.class);
                            i.putExtra("title", name);
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
}
